import { getSetting, chooseAddress, openSetting, showModal, showToast, requestPayment } from "../../utils/asyncWx.js"
import regeneratorRuntime from '../../lib/runtime/runtime'
import { request } from '../../request/index.js'

//authSetting
Page({

  /**
   * 页面的初始数据
   */
  data: {
    address: {},
    cart: [],
    totalPrice: 0,
    totalNum: 0
  },

  onShow() {
    const address = wx.getStorageSync("address")

    let cart = wx.getStorageSync("cart") || []

    cart = cart.filter(v => v.checked)

    // const allChecked = cart.length?cart.every(v => v.checked):false
    this.setData({ address })

    let totalPrice = 0;
    let totalNum = 0;

    cart.forEach(v => {
      totalNum += v.num
      totalPrice += v.num * v.goods_price
    })

    this.setData({
      cart, totalPrice, totalNum, address
    })

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },
  async handleOrderPay() {
    try {
      const token = wx.getStorageSync("token")

      if (!token) {
        wx.navigateTo({
          url: '/pages/auth/index',
        });
        return
      }

      //const header = { Authorization: token }

      const order_price = this.data.totalPrice
      const consignee_addr = this.data.address.all

      const cart = this.data.cart
      let goods = []

      cart.forEach(v => goods.push({
        goods_id: v.goods_id,
        goods_number: v.num,
        goods_price: v.goods_price
      }))

      const orderParam = { order_price, consignee_addr, goods }
      //获取订单编号
      const { order_number } = await request({ url: '/my/orders/create', method: 'POST', data: orderParam })
      //发起预支付请求
      const { pay } = await request({ url: '/my/orders/req_unifiedorder', method: 'POST', data: { order_number } })
      //发起微信支付
      await requestPayment(pay)
      //查询订单状态
      const res = await request({ url: '/my/orders/req_unifiedorder', method: 'POST', data: { order_number } })

      await showToast({title:'支付成功'})

      let newCart=wx.getStorageSync("cart");
      newCart=newCart.filter(v=>!v.checked)
      wx.setStorageSync("cart", newCart);

      wx.navigateTo({
        url: '/pages/order/index'
      });
        
    } catch (error) {
      await showToast({title:'支付失败'})
      console.log(error);
    }
  }

})
